import account from '@/store/account'
import { View, Swiper, SwiperItem, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import moment from 'moment'
import React, { useEffect, useState } from 'react'
import CalendarItem from './calendar-item'
// import http from '@/request'
import { dayType } from '@/types'

interface monthInfoType {
    total: number,
    income: number,
    expense: number,
    month?: string,
    viewHeight?: number,
    accountId?: number
}

// const updateCalendar = async (month, year) => {
//     const list = await http.get(`https://opendata.baidu.com/api.php?tn=wisetpl&format=json&resource_id=39043&cb=callback&query=${year}年${month}`).then(res => {
//         const str = res.data
//         const startIndex = str.indexOf('{');
//         const endIndex = str.lastIndexOf('}') + 1; // 加1是为了包含'}'字符
//         const substring = str.substring(startIndex, endIndex);
//         const resData = JSON.parse(substring)
//         return resData.data[0].almanac.map(item => {
//             let {year, month, day, status, term, lMonth, lDate} = item
//             const date = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`
//             const weekDay = moment(date).day()
//             status = status && Number(status) || 0
//             if (status === 0) {
//                 status = [6, 0].includes(weekDay) ? 3 : 4
//             }
//             return {
//                 date,
//                 status,
//                 term,
//                 lunarCalendar: `${lMonth}月${lDate}`
//             }
//         })
//     })
//     console.log(list);
//     http.post("/work-calendar/update/batch", list)
// }

// const doUpdateCalendar = () => {
//     const months = ['2月', '5月', '8月', '11月']
//     for (let month of months) {
//         updateCalendar(month, 2025)
//     }
// }



const Calendar: React.FC<{
    onMonthActive: (month: monthInfoType) => void,
    onDayActive: (day: dayType) => void,
    initDate?: string,
    refreshKey?: string
}> = ({onMonthActive, onDayActive, initDate, refreshKey}) => {

    const calendarExpandStore = Taro.getStorageSync('calendar-expand')
    const [swiperMonths, swiperSwiperMonths] = useState<(string | undefined)[]>([])
    const [swiperIndex, setSwiperIndex] = useState(0)
    const [isExpand, setIsExpand] = useState(calendarExpandStore !== false)
    const [activeDate, setActiveDate] = useState<dayType>({ id: moment(initDate).format('YYYY-MM-DD'), data: { bills: [] } })
    const [monthInfoData, setMonthInfoData] = useState<monthInfoType>({
        total: 0,
        income: 0,
        expense: 0,
        viewHeight: 0
    })

    // 轮播最多支持往前多少个月
    const preMonthNum = 12
    // const backToady = () => {
    //     VibrateShort()
    //     setSwiperIndex(preMonthNum)
    // }
    const onCalendarActive = (data) => {
        setMonthInfoData(data)
        onMonthActive(data)
    }
    const onExpandChange = () => {
        Taro.setStorageSync('calendar-expand', !isExpand)
        setIsExpand(val => !val)
    }
    const monthChange = (e) => {
        const current = e.target.current
        setSwiperIndex(current)
        // 往后翻页的时候插入月份视图
        if (current === swiperMonths.length - 1) {
            const last = swiperMonths.pop()
            const strArray = [...swiperMonths, last, moment(last).add(1, 'month').format('YYYY-MM-DD')]
            swiperSwiperMonths(strArray)
        }
        // 往前翻页的时候由于插入视图会影响到current，导致显示问题，所以不做额外优化
    }
    
    const selectDay = (day: dayType) => {
        setActiveDate(day)
        onDayActive(day)
    }
    
    // 假日办有更新时手动调用
    useEffect(() => {
        // console.log(doUpdateCalendar);
        // doUpdateCalendar()
    }, [])

    useEffect(() => {
        const array: string[] = []
        for (let i = -preMonthNum; i < 0; i++) {
            array.push(moment(initDate).add(i, 'month').format('YYYY-MM-DD'))
        }
        swiperSwiperMonths([
            ...array,
            moment(initDate).format('YYYY-MM-DD'),
            moment(initDate).add(1, 'month').format('YYYY-MM-DD'),
            moment(initDate).add(2, 'month').format('YYYY-MM-DD'),
        ])
        setSwiperIndex(array.length)        
    }, [account.accountIndex])
    // const days = ['天', '一', '二', '三', '四', '五', '六']
    return <View className="calendar-container need-filter card-background">
    <View className="active-info flex-row text-main-color">
        {
            activeDate.term ? <View className="active-month font-size28">{activeDate.term}·</View> : null
        }
        <View className="active-date font-size24">农历{activeDate.lunarCalendar}</View>
        <View className="flex1"></View>
        {/* <View onClick={backToady} className="back-today flex-row flex-center">
            <View className="text font-size24 border-main-color">本月</View>
        </View> */}
        <View onClick={() => setSwiperIndex(val => val - 1)} className="btn-container flex-column flex-center">
            <View className="btn-bg border-main-color"></View>
            <Text className="iconfont icon-base-left"></Text>
        </View>
        <View onClick={() => setSwiperIndex(val => val + 1)} className="btn-container flex-column flex-center">
            <View className="btn-bg border-main-color"></View>
            <Text className="iconfont icon-base-right"></Text>
        </View>
    </View>
    <Swiper
        className='swiper-container'
        indicatorColor='#999'
        indicatorActiveColor='#333'
        current={swiperIndex}
        style={{ height: (isExpand ? monthInfoData.viewHeight : 264) + 'rpx' }}
        onChange={monthChange}>
        {
            swiperMonths.map((dayStr: string, index) => {
                return <SwiperItem className='swiper-item' key={dayStr + account.activeAccount?.id + (index === swiperIndex ? (refreshKey || '') : '')}>
                    {
                        Math.abs(index - swiperIndex) < 2 ?
                            <CalendarItem
                                isShow={index === swiperIndex}
                                isExpand={isExpand}
                                displayMonth={dayStr}
                                onSelect={selectDay}
                                onActive={onCalendarActive}
                                onExpandChange={onExpandChange}
                                accountId={account.activeAccount?.id}
                                activeDate={activeDate.id || ''}>
                            </CalendarItem> :
                            <View></View>
                    }
                </SwiperItem>
            })
        }
    </Swiper>
</View>
}

export default Calendar